<template>
  <div class="goods-sku-popup">
    <div
      class="goods-sku-popup-main"
      :class="showVisible ? 'goods-sku-popup-show' : ''"
    >
      <template v-if="!initLoading">
        <div class="goods-sku-popup-top">
          <image
            :src="goodsSku.goods_img || goodsDetail.goods_image"
            class="goods-sku-popup-image"
            mode="aspectFill"
          />
          <div class="goods-sku-popup-info">
            <money fw :value="goodsSku.price"></money>
            <div class="flex mt5 fz-small-x">
              <div class="text-grey">库存:</div>
              <div class="ml5">
                {{ goodsStock }}
              </div>
            </div>
            <div class="flex mt5 fz-small-x" v-if="specText != ''">
              <div class="text-grey">规格:</div>
              <div class="ml5">
                {{ specText }}
              </div>
            </div>
          </div>
        </div>

        <!-- 规格 -->
        <div class="goods-sku-popup-attr">
          <div class="goods-sku-popup-attr-list">
            <div v-for="(item, index) in specList" :key="index">
              <div class="goods-sku-popup-attr-title">{{ item.name }}</div>
              <div class="goods-sku-popup-attr-lists">
                <template v-for="(items, idx) in item.value" :key="idx">
                  <div
                    class="goods-sku-popup-attr-item"
                    :class="items.checked ? 'active' : ''"
                    :style="[
                      `background:${items.checked ? DIYTHEME?.deputy_bg : ''}`,
                      `color:${items.checked ? DIYTHEME?.host_bg : ''}`,
                    ]"
                    @click="selectedAttr(item.id, items.id)"
                  >
                    <image
                      class="goods-sku-popup-attr-img"
                      v-if="item.is_img && items.img != ''"
                      :src="items.img"
                    ></image>
                    <div>{{ items.name }}</div>
                  </div>
                </template>
              </div>
            </div>
          </div>

          <!-- 数量 -->
          <div class="goods-sku-popup-number">
            <div class="flex items-center">
              <div>数量</div>
              <div
                class="goods-buy-limit ml5"
                v-if="goodsDetail.buy_limit_status"
              >
                <div>限购</div>
                <div class="ml4">{{ goodsDetail.buy_limit }}件</div>
              </div>
              <div class="goods-buy-least" v-if="goodsDetail.buy_least_status">
                <div>起购</div>
                <div class="ml4">{{ goodsDetail.buy_least }}件</div>
              </div>
            </div>
            <div v-if="goodsStock == 0" class="text-red fz-small">库存不足</div>
            <div v-if="goodsStock > 0">
              <numberBox
                :max="
                  goodsDetail.buy_limit_status &&
                  goodsStock > goodsDetail.buy_limit &&
                  goodsDetail.buy_limit > 0
                    ? goodsDetail.buy_limit
                    : goodsStock
                "
                :min="
                  goodsDetail.buy_least_status && goodsDetail.buy_least > 0
                    ? (goodsStock >= goodsDetail.buy_least ? 1 : goodsDetail.buy_least)
                    : 1
                "
                v-model="goodsNum"
                @change="changeNum"
              ></numberBox>
            </div>
          </div>
        </div>

        <!-- 按钮 -->
        <div class="goods-sku-popup-bottom">
          <div class="goods-sku-popup-empty-stock-btn" v-if="goodsStock < 1">
            库存不足
          </div>
          <template v-if="goodsStock > 0">
            <hover class="goods-sku-popup-bottom-btn">
              <div
                @click.stop="toCart"
                :style="[toCartStyle]"
                class="goods-sku-popup-to-cart"
              >
                加入购物车
              </div>
              <div
                class="goods-sku-popup-cart-count-tips"
                :style="{ color: DIYTHEME?.host_bg }"
                v-if="goodsCartCount > 0"
              >
                购物车已存在 {{ goodsCartCount }} 件
              </div>
            </hover>
            <hover class="goods-sku-popup-bottom-btn">
              <div
                @click.stop="toBuy"
                :style="[toBuyStyle]"
                class="goods-sku-popup-to-cart"
              >
                立即购买
              </div></hover
            >
          </template>
        </div>
      </template>

      <div class="goods-sku-popup-close-btn icon icon-cuo" @click="close"></div>
    </div>
    <div
      class="goods-sku-popup-mask"
      :class="showVisible ? 'goods-sku-popup-mask-show' : ''"
      @click.stop="close"
    ></div>
  </div>
</template>
<script lang="ts">
export default {
  name: "goods-sku",
};
</script>
<script lang="ts" setup>
import { getCurrentInstance, computed, onMounted, ref, StyleValue } from "vue";
import numberBox from "@/components/ui/numberbox/index.vue";
import { onReady } from "@dcloudio/uni-app";
import { getGoodsSku } from "@/api/goods";
import { createCart } from "@/api/cart";

import { Result, ResultError } from "@/types";
import { useConfig } from "@/store";
import { storeToRefs } from "pinia";
const { DIYTHEME } = storeToRefs(useConfig());

const configStore = useConfig();

const props = withDefaults(
  defineProps<{
    goodsId?: number | string;
    bottom?: string | number;
  }>(),
  {
    goodsId: 0,
    bottom: 0,
  }
);

const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["init"]);

const showVisible = ref<boolean>(false);

interface skuType {
  id: string | number;
  price: string | number;
  stock: number;
  sku_attr: string;
  goods_img: string;
}

const goodsDetail = ref<any>();

const goodsSkuList = ref<Array<skuType>>([]);

const goodsSkuId = ref<number | string>(0);

const goodsSkuAttr = ref<string>("");

const goodsCartCount = ref<number>(0)

// 已选规格
const goodsSku = ref<skuType>({
  id: 0,
  price: 0.0,
  stock: 0,
  sku_attr: "",
  goods_img: "",
});

const goodsStock = ref<number | string>(1);

const goodsNum = ref<number | string>(1);

// 规格信息
const specText = ref<string>("默认");

const specList = ref<any>([]);

onReady(() => {});

const toInit = () => {
  getGoodsSku({
    id: props.goodsId,
  })
    .then((res: Result) => {
      goodsDetail.value = res.data.detail;
      goodsSku.value = res.data.sku;
      goodsSkuList.value = res.data.detail.sku;
      specList.value = res.data.spec_list;
      goodsCartCount.value = res.data.goods_cart_count
      skuFilter(goodsSku.value.sku_attr);
      initManySpecData(specList.value, goodsSku.value.sku_attr);
      initLoading.value = false;
      showVisible.value = true;
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

const skuFilter = (skuAttr: string) => {
  var skuItem = goodsSkuList.value.find((item: skuType) => {
    return item.sku_attr == skuAttr;
  });
  if (typeof skuItem === "object") {
    goodsSku.value = skuItem;
    goodsSkuId.value = skuItem.id;
    goodsSkuAttr.value = skuItem.sku_attr;
    goodsStock.value = skuItem.stock;
    var stockNum = 1;
    if (goodsDetail.value.buy_least_status && goodsDetail.value.buy_least > 0) {
      stockNum = goodsStock.value >=  goodsDetail.value.buy_least ? 1 : goodsDetail.value.buy_least;
    } else if (
      goodsDetail.value.buy_limit_status &&
      goodsDetail.value.buy_limit > 0
    ) {
      stockNum = goodsDetail.value.buy_limit;
    } else if (goodsNum.value > skuItem.stock) {
      stockNum = skuItem.stock;
    }
    goodsNum.value = stockNum;
  }
};

// 规格
const attrArr = ref<any>();

/**
 * 初始化商品多规格
 */
const initManySpecData = (data: any, skuAttr: string) => {
  var skuAttrArr = skuAttr.split(":").sort((a: any, b: any) => {
    return a - b;
  });
  specText.value = "";
  for (let i in data) {
    for (let j in data[i].value) {
      if (skuAttrArr.indexOf(data[i].value[j].id.toString()) >= 0) {
        data[i].value[j].checked = true;
        specText.value += data[i].name + "-" + data[i].value[j].name + ";";
      }
    }
  }
};

// 选择规格
const selectedAttr = (specId: number, valueId: number) => {
  specText.value = "";
  attrArr.value = [];
  for (let i in specList.value) {
    specText.value += specList.value[i].name;
    var attrText = "";
    for (let j in specList.value[i].value) {
      if (specId == specList.value[i].id) {
        specList.value[i].value[j].checked = false;
        if (valueId == specList.value[i].value[j].id) {
          specList.value[i].value[j].checked = true;
        }
      }
      if (specList.value[i].value[j].checked == true) {
        attrArr.value.push(specList.value[i].value[j].id);
        attrText = specList.value[i].value[j].name;
      }
    }
    specText.value += "-" + attrText + ";";
  }
  console.log("更新商品规格信息");
  // 更新商品规格信息
  skuFilter(
    attrArr.value
      .sort((a: number, b: number) => {
        return a - b;
      })
      .join(":")
  );
};

const changeNum = (obj: { value: string | number }) => {
  goodsNum.value = obj.value;
};

//加入购物车
const toCart = (e: any) => {
  if (goodsDetail.value.goods_cart_stock >= goodsStock.value) {
    $utils.errorMsg(
      "购物车已经加入了" +
        goodsDetail.value.goods_cart_stock +
        "件，不能再加入了哦,赶紧去购买吧"
    );
    return false;
  }
  if (goodsNum.value < 1) {
    wx.showToast({
      title: "请输入正确的数量",
      icon: "none",
      duration: 2000,
    });
    return false;
  }
  createCart({
    goods_id: props.goodsId,
    goods_num: goodsNum.value,
    goods_sku_id: goodsSkuId.value,
  })
    .then((res: Result) => {
      $utils.successMsg(res.message);
      close();
      emit("init");
    })
    .catch((err: ResultError) => {
      $utils.errorMsg(err);
    });
};

// 立即购买
const toBuy = () => {
  if (goodsNum.value < 1) {
    $utils.errorMsg("库存不足或数量不对");
    return false;
  }
  $utils.routeRedirectTo("/otherpages/order/buy/index", {
    goods_id: props.goodsId,
    goods_num: goodsNum.value,
    goods_sku_id: goodsSkuId.value,
  });
};

const initLoading = ref<boolean>(true);

const open = () => {
  toInit();
};

const close = () => {
  showVisible.value = false;
};

onMounted(() => {});
defineExpose({ open, close });

const toCartStyle = computed<StyleValue>(() => {
  var style = {
    background: DIYTHEME?.value?.deputy_bg,
    color: DIYTHEME?.value?.host_bg,
  };
  if (goodsDetail.value.goods_cart_stock >= goodsStock.value) {
    style.background = "#f0f0f0";
    style.color = "#999";
  }
  return style;
});
const toBuyStyle = computed<StyleValue>(() => {
  var style = {
    background: `linear-gradient(to right,${DIYTHEME.value?.host_bg2},${DIYTHEME.value?.host_bg})`,
    color: DIYTHEME?.value?.host_color,
  };
  if (goodsDetail.value.goods_cart_stock >= goodsStock.value) {
    style.background = "#f0f0f0";
    style.color = "#999";
  }
  return style;
});
</script>


<style scoped>
.goods-sku-popup-main {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 99999;
  width: calc(100% - 40rpx);
  visibility: hidden;
  transform: translate3d(0, 100%, 0);
  transform-origin: center;
  transition: all 0.3s ease-in-out;
  background: #ffffff;
  padding: 20rpx;
  bottom: 0;
}
.goods-sku-popup-show {
  transform: translate3d(0, 0, 0);
  visibility: visible;
}
.goods-sku-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.6);
  z-index: 99996;
  transition: all 0.3s ease-in-out;
  opacity: 0;
  visibility: hidden;
}
.goods-sku-popup-mask-show {
  opacity: 1;
  visibility: visible;
}

.goods-sku-popup-top {
  position: relative;
}
.goods-sku-popup-top .goods-sku-popup-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: var(--base-radius-default);
}
.goods-sku-popup-top .goods-sku-popup-info {
  width: calc(100% - 180rpx);
  position: absolute;
  right: 0;
  bottom: 10rpx;
}

/* spec attr */
.goods-sku-popup-attr {
  max-height: 400rpx;
  overflow-x: scroll;
}
.goods-sku-popup-attr-list {
  padding: 20rpx 0;
  box-sizing: border-box;
}
.goods-sku-popup-attr-title {
  padding: 10rpx 0;
}
.goods-sku-popup-attr-lists {
  padding: 10rpx 0;
}
.goods-sku-popup-attr-item {
  max-width: 100%;
  height: 50rpx;
  line-height: 50rpx;
  display: -webkit-inline-flex;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: #f7f7f7;
  padding: 0 20rpx;
  box-sizing: border-box;
  border-radius: var(--base-radius-small);
  margin-right: 15rpx;
  margin-bottom: 15rpx;
  color: #777;
  font-size: var(--base-size-small);
}
.goods-sku-popup-attr-item.active {
  position: relative;
}
.goods-sku-popup-attr-img {
  height: 40rpx;
  width: 40rpx;
  margin-right: 10rpx;
}

.goods-sku-popup-close-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 80rpx;
  height: 80rpx;
  border-radius: 80rpx;
  font-size: var(--base-size-default);
  line-height: 80rpx;
  text-align: center;
  color: #000;
  font-weight: bold;
}

.goods-sku-popup-number {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0 50rpx 0;
  box-sizing: border-box;
}

.goods-sku-popup-bottom {
  display: flex;
  margin: 20rpx 0;
  justify-content: space-between;
}
.goods-sku-popup-bottom-btn {
  width: calc(50% - 20rpx);
  text-align: center;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: var(--base-radius-small);
  position: relative;
  font-size: var(--base-size-default);
}
.goods-sku-popup-to-cart,
.goods-sku-popup-to-buy {
  border-radius: var(--base-radius-small);
}
.goods-sku-popup-empty-stock-btn {
  height: 70rpx;
  width: 100%;
  background: #f0f0f0;
  color: #000000;
  border-radius: var(--base-radius-small);
  text-align: center;
  line-height: 70rpx;
}
.goods-sku-popup-cart-stock-tips {
  position: absolute;
  height: 26rpx;
  line-height: 24rpx;
  font-size: var(--base-size-small-x);
  z-index: 1;
  top: -35rpx;
  left: 0rpx;
}
.goods-sku-popup-cart-count-tips{
  position: absolute;
  /* background: #fff; */
  /* padding:0 10rpx; */
  height: 26rpx;
  line-height: 24rpx;
  /* border-radius: 5rpx; */
  font-size:var(--base-size-small-xx);
  /* border:1rpx solid #999999; */
  z-index: 1;
  top: -35rpx;
  left:0rpx;
}
</style>